﻿using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Models;
using DFGK_WMS.WebAPI.AttributeFile;
using DFGK_WMS.WebAPI.Controllers.Result;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Security.Claims;

namespace DFGK_WMS.WebAPI.Controllers.收货管理
{
    /// <summary>
    /// 收货管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TReceivingBillController : ControllerBase
    {
        private readonly ILogRepository logRepository;

        public ITReceivingBillRepository TreceService { get; }

        public TReceivingBillController(ITReceivingBillRepository treceService, ILogRepository logRepository)
        {
            TreceService = treceService;
            this.logRepository = logRepository;
        }


        /// <summary>
        /// 显示收货管理
        /// </summary>
        /// <param name="supplierId"></param>
        /// <param name="status"></param>
        /// <param name="warehouseId"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetReceivingBillList(int supplierId=0, int status = 3, int warehouseId = 0, int pageIndex=1, int pageSize=10)
        {
            if(pageIndex<=0 || pageSize<=0)
            {
                return Ok(BaseResult.Result("400", "分页条件有误！"));
            }
            int totalCount;

            var list = TreceService.GetReceivingBillList(supplierId, status, warehouseId, pageIndex, pageSize, out totalCount);

            if (list != null)
            {
                return Ok(BaseResult.Result(list, "查询成功！", "200", totalCount));
            }
            return Ok(BaseResult.Result(null, "查询失败！", "500", 0));
        }

        /// <summary>
        /// 添加收货单
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        [HttpPost]
        [HttpIdempotent(WaitMillisecond = 10000, CacheMillisecond = 3000)]
        public IActionResult AddReceivingBill(TReceivingBill m)
        {
            if (string.IsNullOrEmpty(m.BillNo))
            {
                return Ok(BaseResult.Result("400", "单号不能为空！"));
            }
            string message = "";
            bool IsOK = TreceService.AddReceivingBill(m,out message);
            if (IsOK)
            {
                string uname = HttpContext.User.FindFirstValue("UserName");
                string runame = HttpContext.User.FindFirstValue("RealName");
                int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                string? ip = HttpContext.Connection.RemoteIpAddress?.ToString();
                TLog logg = new TLog();
                logg.LogType = 1;
                logg.ActionType = 4;
                logg.ModuleName = "收货管理";
                logg.UserName = uname;
                logg.RealName = runame;
                logg.UserId = uid;
                logg.Description = uname + "创建了收货单" + m.BillNo;
                //获取前端IP地址
                logg.Ipaddress = ip;

                logRepository.AddTLod(logg);
                return Ok(BaseResult.Result(true, "添加成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "添加失败！"+message, "500"));
        }


        /// <summary>
        /// 根据Id获取对象
        /// </summary>
        /// <param name="rid"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetTReceivingBillById(int rid)
        {
            if (rid <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            var mobj = TreceService.GetTReceivingBillById(rid);
            if (mobj != null)
            {
                return Ok(BaseResult.Result(mobj, "获取成功", "200"));
            }
            return Ok(BaseResult.Result(null, "获取失败！", "500"));
        }

        /// <summary>
        /// 根据物料分类id返回物料
        /// </summary>
        /// <param name="mid"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetRidById(int mid)
        {
            if (mid <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            var mobj = TreceService.GetRidById(mid);
            if (mobj != null)
            {
                return Ok(BaseResult.Result(mobj, "获取成功", "200"));
            }
            return Ok(BaseResult.Result(null, "获取失败！", "500"));
        }

        /// <summary>
        /// 收货入库
        /// </summary>
        /// <returns></returns>
        [HttpPut]
        [HttpIdempotent(WaitMillisecond = 10000, CacheMillisecond = 3000)]
        public IActionResult AddReceivingOrderDateil(ReceivingBillOrderDto m)
        {

            if(m.Id<=0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            m.NowUserId = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
            m.NowUserRealName = HttpContext.User.FindFirstValue("UserName");
            string message = "";
            bool IsOK = TreceService.AddPDAReceivingOrderDateil(m,out message);
            if (IsOK)
            {
                return Ok(BaseResult.Result(true, "保存成功！", "200"));
            }
            return Ok(BaseResult.Result(false, message, "500"));
        }
        
        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="rid"></param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult UpdReceivingBillStatus(int rid)
        {
            if (rid <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            bool IsOK = TreceService.UpdReceivingBillStatus(rid);
            if (IsOK)
            {
                return Ok(BaseResult.Result(true, "保存成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "保存失败！", "500"));
        }

        /// <summary>
        /// RFID添加收货单（海宁）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddCheck(AddReceivingBilDTO addReceivingBilDTO)
        {
            var IsOk = TreceService.AddCheck(addReceivingBilDTO,out string Message);
            if (IsOk)
            {
                return Ok(BaseResult.Result(true, "保存成功！", "200"));
            }
            return Ok(BaseResult.Result(false, Message, "500"));
        }

        /// <summary>
        /// 返回验收单下的所有物料条码（海宁）
        /// </summary>
        /// <param name="ChackNumber"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetCheckMaterialCode(string ChackNumber)
        {
            var receivingBill = TreceService.GetCheckMaterialCode(ChackNumber);
            var data = receivingBill.BillDetailList.Select(r => new
            {
                r.MaterialCode,
                r.MaterialName
            });
            if (data is null || data.Count() == 0)
            {
                return Ok(BaseResult.Result(false, "生成失败未查出物料", "500"));
            }
            return Ok(BaseResult.Result(data, "查询成功！", "200"));
        }

    }
}
